import time

from etc.app_config import AppConfig
from utils.logger_helper import LoggerHelper
from task_server.task_runner import TaskRunner
from task_server.task_item import TaskItem

logger = LoggerHelper.get_logger()


class TaskAdmin(object):
    TASK_CHECK_INTERVAL_SECONDS = AppConfig.TASK_CHECK_INTERVAL_SECONDS

    @classmethod
    def loop_run_task(cls):
        loop_times = 0
        while True:
            loop_times += 1
            logger.info("开始第{}次任务调度".format(loop_times))
            running_tasks = TaskItem.get_running_tasks()
            for task_item in running_tasks:
                task_runner = TaskRunner(task_item=task_item)
                task_runner.check_task()
            pending_tasks = TaskItem.get_pending_tasks()
            for task_item in pending_tasks:
                task_runner = TaskRunner(task_item=task_item)
                task_runner.start_task()
            stopping_tasks = TaskItem.get_stopping_tasks()
            for task_item in stopping_tasks:
                task_runner = TaskRunner(task_item=task_item)
                task_runner.stop_task()
            logger.info("完成第{}次任务调度".format(loop_times))
            time.sleep(cls.TASK_CHECK_INTERVAL_SECONDS)
        pass
